import urllib
import json
from urllib.request import Request, urlopen
from urllib.parse import urlencode

from app.core.config import DB_CMDB_URL
from app.core.config import DB_CMDB_USER
from app.core.config import DB_CMDB_PASSWORD

from app.core.config import DB_PLATFORM_URL
from app.core.config import DB_PLATFORM_USER
from app.core.config import DB_PLATFORM_PASSWORD


def message_format(body):
    # log.info(str(body))
    try:
        # message = bytes.decode(body)
        message = str(body)
        # message1 = json.loads(message)
        message_eval = eval(message)
        for key, value in message_eval.items():
            if isinstance(value, bytes):
                message_eval.update({key: str(value, encoding="utf-8")})
        return message_eval
    except Exception as e:
        # log.exception(str(e))
        return


def get_token(user_name, password, call_system):
    if call_system == 'cmdb':
        base_url = DB_CMDB_URL
        auth_url = '/auth/token'
    elif call_system == 'dbpt':
        base_url = DB_PLATFORM_URL
        auth_url = "/auth/token/user_login"
    else:
        return
    message = {
        'eauth': "pam",
        "username": user_name,
        "password": password
    }
    request_url = "{base_url}{auth_url}".format(base_url=base_url,
                                                auth_url=auth_url)
    request = Request(request_url, urlencode(message).encode())
    body = urlopen(request).read().decode()
    token_info = message_format(body)
    token = token_info.get("token")
    # log.debug(token)
    return "bearer " + token


def info_interactive_with_pt(suffix_url,
                             args_send,
                             call_system='cmdb',
                             method="POST"):
    if call_system == 'cmdb':
        user_name = DB_CMDB_USER
        password = DB_CMDB_PASSWORD
        base_url = DB_CMDB_URL
    elif call_system == 'dbpt':
        user_name = DB_PLATFORM_USER
        password = DB_PLATFORM_PASSWORD
        base_url = DB_PLATFORM_URL
    else:
        return
    token_get = get_token(user_name=user_name, password=password, call_system=call_system)
    args_send_format = json.dumps(args_send)
    request_url = "{}{}".format(base_url, suffix_url)
    req = urllib.request.Request(url=request_url,
                                 data=bytes(
                                     args_send_format.encode("utf-8")),
                                 method=method)

    # log.debug(request_url)
    req.add_header("Content-type", "application/json; charset=UTF-8")
    req.add_header("Authorization", token_get)
    with urllib.request.urlopen(req) as resp:
        response_data = json.loads(resp.read().decode("utf-8"))
        # log.debug(response_data)
    return response_data


def interactive_with_backup_service(base_url, args_send, method='POST'):
    # base_url = "http://10.200.11.27:5001/audit_api/sql_backup"
    # request_url = "{}{}".format(base_url, suffix_url)

    args_send_format = json.dumps(args_send)
    req = urllib.request.Request(url=base_url,
                                 data=bytes(
                                     args_send_format.encode("utf-8")),
                                 method=method)
    # log.debug(request_url)
    # req.add_header("Content-type", "application/json; charset=UTF-8")
    # req.add_header("Authorization", token_get)
    req.add_header("Content-type", "application/json; charset=UTF-8")

    with urllib.request.urlopen(req) as resp:
        response_data = json.loads(resp.read().decode("utf-8"))
        return response_data
